#!/usr/bin/env python
# -*- coding: utf-8 -*-
#### Copyright (c) 2008 Clóvis Fabrício Costa - All rights reserved

import subprocess

class Shell(object):
    def __init__(self, param=None, debug=False):
        if param is None:
            param = []
        self._pysh_param = param
        self._pysh_debug = debug
        
    def _pysh_pdebug(self, msg):
        if self._pysh_debug:
            print "DEBUG: %s" % msg

    def __iter__(self):
        return iter(str(self).splitlines())

    def _pysh_add(self, *params):
        tmp = self._pysh_param[:]
        for param in params:
            try:
                tmp.extend(param._pysh_param)
            except AttributeError:
                tmp.append(str(param))
        return Shell(tmp, debug=self._pysh_debug)

    def __getattr__(self, attr):
        if attr.startswith('_pysh_'):
            return super(Shell, self).__getattr__(self, attr)
        else:
            return self._pysh_add(attr.replace('_', '-'))

    def __getitem__(self, item):
        return self._pysh_add(item)
    def __call__(self, extra_param=None, envio='', **kwds):
        if extra_param is not None:
            run = self._pysh_add(extra_param)
        else:
            run = self
        return run._pysh_run(run._pysh_param, envio=envio, **kwds)

    def _pysh_run(self, cmd, envio='', **kwds):
        self._pysh_pdebug('%r mandando %r' % (cmd, envio))
        return subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                                stderr=subprocess.STDOUT, 
                                stdin=subprocess.PIPE, 
                                **kwds).communicate(envio)[0]
    def __str__(self):
        return self._pysh_run(self._pysh_param)

    def __repr__(self):
        return '$ %s' % ' '.join(self._pysh_param)

if __name__ == '__main__':        
    s = Shell(debug=True)
    ls = s.ls
    l = ls._l
